var url = require('url');
//导入querystring模块（解析post请求数据）
var querystring = require('querystring');

//封装方法改变res 绑定res.send()
function changeRes(res) {
    res.send = function (data) {
        res.writeHead(200, {
            "Content-Type": "text/html;charset=utf-8;"
        });
        res.end(data);
    }
}
var Server = function () {
    var G = this; /*全局变量*/
    this._get = {}; //处理get请求
    this._post = {}; //处理post请求

    var app = function (req, res) {
        changeRes(res);
        //获取路由
        var pathname = url.parse(req.url).pathname;
        if (!pathname.endsWith('/')) {
            pathname = pathname + '/';
        }
        //获取请求的方式 get post
        var method = req.method.toLowerCase();
        if(pathname!='/favicon.ico/'){
            console.log(method);
            console.log(pathname);
            console.log(G['_' + method][pathname]);
            
            if (G['_' + method][pathname]) {
                if (method == 'post') {
                    var postStr = '';
                    req.on('data', function (chunk) {
                        postStr += chunk;
                        try {
                            postStr = JSON.parse(postStr);
                        } catch (e) {
                            postStr = querystring.parse(postStr);
                        }
                    });
    
                    req.on('end', function (err, chunk) {
                        req.body = postStr; /*表示拿到post的值 */
                        G['_' + method][pathname](req, res); //执行方法
                    });
                } else {
                    G['_' + method][pathname](req, res);
                }
            } else {
                res.end('no router');
            }
        }
    }

    app.get = function (string, callback) {
        if (!string.endsWith('/')) {
            string = string + '/';
        }
        if (!string.startsWith('/')) {
            string = '/' + string;

        }
        G._get[string] = callback;
    }

    app.post = function (string, callback) {
        if (!string.endsWith('/')) {
            string = string + '/';
        }
        if (!string.startsWith('/')) {
            string = '/' + string;
        }
        G._post[string] = callback;
    }

    return app;
}

module.exports = Server();